package online3;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class CalcServer {
    private DatagramSocket socket=null;
    public CalcServer(int port) throws SocketException {
        socket=new DatagramSocket(port);
    }
    public void start() throws IOException {
        System.out.println("服务器启动！");
        while (true){
            DatagramPacket requestPacket=new DatagramPacket(new byte[4096],4096);
            socket.receive(requestPacket);
            String requset=new String(requestPacket.getData(),0,requestPacket.getLength());
            String response=process(requset);
            DatagramPacket responsePacket=new DatagramPacket(response.getBytes(),response.getBytes().length,
                    requestPacket.getSocketAddress());
            socket.send(responsePacket);
            String log=String.format("[%s:%d] rep: %s; resp:%s",requestPacket.getAddress().toString(),
                    requestPacket.getPort(),requset,response);
            System.out.println(log);
        }
    }
    public String process(String request){
        String[] tokens=request.split(";");
        if (tokens.length!=3){
            return "[请求格式出错!]";
        }
        String st="";
        int num1=Integer.valueOf(tokens[0]);
        int num2=Integer.valueOf(tokens[1]);
        switch (tokens[2]){
            case "+":
                st=st+(num1+num2);
                break;
            case "-":
                st=st+(num1-num2);
                break;
            case "*":
                st=st+(num1*num2);
                break;
            case "/":
                st=st+(num1/num2);
                break;
            default:
                st=st+"运算符错误！";
                break;
        }
        return st;
    }
    public static void main(String[] args) throws IOException {
        CalcServer server=new CalcServer(9090);
        server.start();
    }
}
